/**
 * 新闻点击过滤器
 * 点击一次：点击率加 1
 */
package com.wsj.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wsj.service.IHomeSiteNewsServ;
import com.wsj.util.exception.BusinessException;
import com.wsj.web.vo.homeSite.HomeSiteNews;

public class HomeSiteNewsFilter implements Filter
{
	
	protected FilterConfig filterConfig = null;
	protected String toPage = null;
	protected String errorPage = "/error/fileNotFond.html";
	
	private Log logger = LogFactory.getLog(this.getClass());
	protected IHomeSiteNewsServ homeSiteNewsServImpl;

	
	public void destroy() 
	{
		 this.toPage  = null;
	     this.filterConfig = null;	
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
	{
		HttpServletRequest httpReq = (HttpServletRequest)request;
    	HttpServletResponse httpResp = (HttpServletResponse)response;
    	
    	//校验请求路径
    	if(checkPath(httpReq))
    	{ 		
    		ServletContext context = filterConfig.getServletContext();
    		logger.error("\n\n RequestURI:" + httpReq.getRequestURI());
    		
    		//解析出的查询路径"/html/news/news_174.html"
    		String queryPath = httpReq.getRequestURI();
    		
    		//解析出id
    		String idStr = this.parseId(queryPath);
    		
    		// 新闻详细内容
    		if(idStr != null){
    			Integer id = Integer.parseInt(idStr);
    			HomeSiteNews hsNews;
				try {
					hsNews = this.homeSiteNewsServImpl.getHomeSiteNewsById(id);
					if(hsNews.getHits() == null){
						hsNews.setHits(new Integer(0));
					}
					hsNews.setHits(hsNews.getHits()+1);
					homeSiteNewsServImpl.update(hsNews);
				} catch (BusinessException e) {
					e.printStackTrace();
				}
    		}
    		
            RequestDispatcher rd = context.getRequestDispatcher(toPage+idStr);
            if (rd == null) 
            {
                httpResp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"The page doesn't exist");
            }
            
    	}
        chain.doFilter(request, response);
		
	}

	
	/***
	 * 解析出请求路径中的id
	 * @param queryPath
	 * @return
	 */
	private String parseId(String queryPath) 
	{
		String id = "";
		if(queryPath != null && !queryPath.equals(""))
		{
			Integer size = queryPath.lastIndexOf("/");
			String withHtml = queryPath.substring(size+1, queryPath.length());
			
			//将news_134.html 解析 出新闻ID 134  
			id=withHtml.substring(5,withHtml.length()-5);
		}
		
		return id;
	}

    
    
	
	/****
	 * 校验请求路径
	 * @param httpReq
	 * @return
	 */
	private boolean checkPath(HttpServletRequest httpReq) 
	{
		String requestURI=httpReq.getRequestURI();
		boolean isok=false;
		if(requestURI.indexOf("/html/news/")!=-1 && requestURI.indexOf(".html")!=-1 )
		{
			isok = true;
		}
		return isok;
	}

	
	/***
	 * 初始化
	 */
	@SuppressWarnings("unchecked")
	public void init(FilterConfig filterConfig) throws ServletException 
	{
		    this.filterConfig = filterConfig;
	        this.toPage  = filterConfig.getInitParameter("toPage");
	        if(toPage==null)
	        {
	                throw new ServletException("toPage init param missing");
	        }
		
	}
	
	public IHomeSiteNewsServ getHomeSiteNewsServImpl() {
		return homeSiteNewsServImpl;
	}

	public void setHomeSiteNewsServImpl(IHomeSiteNewsServ homeSiteNewsServImpl) {
		this.homeSiteNewsServImpl = homeSiteNewsServImpl;
	}

	public String getErrorPage() {
		return errorPage;
	}

	public void setErrorPage(String errorPage) {
		this.errorPage = errorPage;
	}

	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	public String getToPage() {
		return toPage;
	}

	public void setToPage(String toPage) {
		this.toPage = toPage;
	}


}
